package me.pinion.model;

import com.jfinal.plugin.activerecord.*;
import me.pinion.model.annotation.TableBind;

import java.util.List;

@TableBind(table = "x_like")
public class Like extends XModel<Like> {
    public static Like dao = new Like();

    public Long count(XModel<? extends XModel<?>> model) {
        return Db.findFirst("SELECT count(l.id) AS like_count FROM x_like as l WHERE l.target_type = ? AND l.target_id = ?", model.getModelId(), model.getId()).getLong("like_count");
    }


    public Like hasLike(XModel<? extends XModel<?>> model, User user) {
        return Like.dao.findFirst(
                "SELECT * FROM x_like WHERE user=? AND target_id=? AND target_type=?"
                , user.getId()
                , model.getId()
                , ModelType.dao.getByClass(model.getClass()).getId());
    }

    public <T extends XModel<T>> List<T> hasLike(Class<T> clazz, User user) {
        ModelType type = ModelType.dao.getByClass(clazz);
        return type.<T>getModelDAO().find("SELECT t.* FROM " + type.getModelTable() + " AS t WHERE t.id in(SELECT l.target_id FROM x_like AS l WHERE l.user=? AND l.target_type=?)", user.getId(), type.getId());
    }
}
